package com.mxchip.livestarmobile.mobile.repository

import android.content.Context
import android.util.Log
import com.duobeiyun.paassdk.bean.AVideoState
import com.duobeiyun.paassdk.bean.SolNetworkInformation
import com.duobeiyun.paassdk.live.DbyEngine
import com.duobeiyun.paassdk.live.DbyEventHandler
import com.duobeiyun.paassdk.live.impl.config.ExtraConfig
import com.duobeiyun.paassdk.media.DBAudioSource
import com.duobeiyun.paassdk.media.DBIVideoCustomRender
import com.duobeiyun.paassdk.media.DBVideoSource
import com.mxchip.livestarmobile.mobile.graham.SDKInterface
import org.json.JSONArray
import org.json.JSONObject
import java.lang.Exception

object DbyEngineRepository : SDKInterface {

    private var currentUid: String? = null
    private var currentNickname: String? = null

    private var dbyEngine: DbyEngine? = null

    fun init(context: Context, appId: String, appKey: String) {
        dbyEngine = DbyEngine.createInstance(context.applicationContext, appKey, appId, dbyEventHandler)

        val config: ExtraConfig = ExtraConfig.Builder()
                .setDualStreamTypeDefault(0)
                .setStreamOptionDefault(true)
                .setEnableAutoRepeatSend(false)
                .setFecRate(10)
                .setAudioFecCache(20)//默认是40；
                .setVideoFecCache(10)//默认20；
                .build()
        dbyEngine?.setExtraConfig(config)
    }

    fun destroy() {
        currentUid = null
        currentNickname = null
        mSDKEventListener = null
        dbyEngine?.destroy()
        dbyEngine = null
    }

    fun muteRemoteAudioStream(uid: String, deviceName: String, b: Boolean): Int {
        return dbyEngine?.muteRemoteAudioStream(uid, deviceName, b) ?: 0
    }

    fun setRemoteVideoCustomRenderer(uid: String, deviceName: String, dbiVideoCustomRender: DBIVideoCustomRender) {
        dbyEngine?.setRemoteVideoCustomRenderer(uid, deviceName, dbiVideoCustomRender)
    }

    fun muteRemoteVideoStream(uid: String, deviceName: String, b: Boolean): Int {
        return dbyEngine?.muteRemoteVideoStream(uid, deviceName, b) ?: 0
    }

    fun leaveChannel() {
        dbyEngine?.leaveChannel()

        currentUid = null
        currentNickname = null
    }

    fun joinChannel(roomId: String, uid: String, nickname: String) {
        dbyEngine?.joinChannel(roomId, uid, nickname)

        currentUid = uid
        currentNickname = nickname
    }

    fun recovery() {
        dbyEngine?.recovery()
    }

    fun enableLocalCamera(deviceName: String, enable: Boolean): Int {
        return dbyEngine?.enableLocalCamera(deviceName, enable) ?: 0
    }

    fun enableLocalAudio(deviceName: String, enable: Boolean): Any {
        return dbyEngine?.enableLocalAudio(deviceName, enable) ?: 0
    }

    fun setDBVideoSource(videoSource: DBVideoSource) {
        dbyEngine?.setDBVideoSource(videoSource)
    }

    fun setDBAudioSource(audioSource: DBAudioSource, b: Boolean) {
        dbyEngine?.setDBAudioSource(audioSource, b)
    }

    fun setDefaultAudioRoutetoSpeakerphone( b: Boolean) {
        dbyEngine?.setDefaultAudioRoutetoSpeakerphone( b)
    }

    fun setSDKEventListener(handler: SDKEventListenerWrap?) {
        mSDKEventListener = handler
    }

    private var mSDKEventListener: SDKEventListenerWrap? = null

    private val dbyEventHandler: DbyEventHandler = object : DbyEventHandler() {

        /*override fun onlineUserCount(count: Int) {
            dbyEventHandlerWrap?.onlineUserCount(count)
        }*/

        override fun onNetWorkDelay(delay: Int) {
            mSDKEventListener?.onNetWorkDelay(delay)
        }

        /*override fun getDumpProtocol(protocol: String) {
            dbyEventHandlerWrap?.getDumpProtocol(protocol)
        }

        override fun onAvActions(videoUp: Double, videoDown: Double, fps: Double) {
            dbyEventHandlerWrap?.onAvActions(videoUp, videoDown, fps)
        }

        override fun onClientRoleChanged(oldRole: Int, newRole: Int) {
            dbyEventHandlerWrap?.onClientRoleChanged(oldRole, newRole)
        }

        override fun onSessionStatsCallback(sessionSts: SessionStats) {
            dbyEventHandlerWrap?.onSessionStatsCallback(sessionSts)
        }*/

        override fun onNetworkQuality(userId: String, txQuality: Int, rxQuality: Int) {
            mSDKEventListener?.onNetworkQuality(userId, txQuality, rxQuality)
        }

        /*
        override fun onLastmileQuality(quality: Int) {
            dbyEventHandlerWrap?.onLastmileQuality(quality)
        }

        override fun onRemoteVideoStatsCallback(remotestats: RemoteVideoStats) {
            dbyEventHandlerWrap?.onRemoteVideoStatsCallback(remotestats)
        }

        override fun onLocalVideoStatsCallback(localstats: LocalVideoStats) {
            dbyEventHandlerWrap?.onLocalVideoStatsCallback(localstats)
        }*/

        override fun onConnectionStateChanged(code: Int) {
            mSDKEventListener?.onConnectionStateChanged(code)
        }

        /*override fun onAudioVolumeIndication(list: List<DBVolumeInfo>, totalVolume: Int) {
            dbyEventHandlerWrap?.onAudioVolumeIndication(list, totalVolume)
        }*/

        override fun onBroadCastMessage(uid: String, message: String) {
            Log.e("DbyEngineRepository", "onBroadCastMessage $uid $message $currentUid $currentNickname")
            try {
                val jsonObject = JSONObject(message)
                val type = jsonObject.getString("type")

                if(type == "mgtMuteCamera") {
                    val data = jsonObject.getJSONArray("data")
                    val uids = Array(data.length()) {
                        data.getString(it)
                    }
                    if(currentUid != null && uids.contains(currentUid)) {
                        mSDKEventListener?.onMgtMuteCameraEvent()
                    }
                }

                if(type == "mgtMuteAudio") {
                    val data = jsonObject.getJSONArray("data")
                    val uids = Array(data.length()) {
                        data.getString(it)
                    }
                    if(currentUid != null && uids.contains(currentUid)) {
                        mSDKEventListener?.onMgtMuteAudioEvent()
                    }
                }

                if(type == "mgtMuteShareContent") {
                    val data = jsonObject.getJSONArray("data")
                    val uids = Array(data.length()) {
                        data.getString(it)
                    }
                    if(currentUid != null && uids.contains(currentUid)) {
                        mSDKEventListener?.onMgtMuteShareContentEvent()
                    }
                }

            } catch (e: Exception) { }
        }

        /*override fun onLocalAudioStateChanged(state: Int, err: Int) {
            dbyEventHandlerWrap?.onLocalAudioStateChanged(state, err)
        }

        override fun onLocalVideoStateChanged(state: Int, err: Int) {
            dbyEventHandlerWrap?.onLocalVideoStateChanged(state, err)
        }*/


        //////
        /*override fun onError(errcode: Int) {
            dbyEventHandlerWrap?.onError(errcode)
        }

        override fun onStatusCode(code: Int) {
            dbyEventHandlerWrap?.onStatusCode(code)
        }*/

        /*override fun onStatusMessage(msg: String) {
            dbyEventHandlerWrap?.onStatusMessage(msg)
        }*/

        override fun onJoinChannelSuccess(channel: String, userId: String, userName: String) {
            mSDKEventListener?.onJoinChannelSuccess(channel, userId, userName)
        }

        /*override fun onRejoinChannelSuccess(channel: String, userId: String, userName: String) {
            dbyEventHandlerWrap?.onRejoinChannelSuccess(channel, userId, userName)
        }*/

        override fun onLeaveChannel() {
            mSDKEventListener?.onLeaveChannel()
        }

        override fun onUserJoined(uid: String, userName: String) {
            mSDKEventListener?.onUserJoined(uid, userName)
        }

        override fun onUserLeave(uid: String) {
            mSDKEventListener?.onUserLeave(uid)
        }

        /*override fun onClientkickOff() {
            dbyEventHandlerWrap?.onClientkickOff()
        }*/


        /*override fun onFirstRemoteVideoDecoded(uid: String, deviceName: String, width: Int, height: Int) {
            dbyEventHandlerWrap?.onFirstRemoteVideoDecoded(uid, deviceName, width, height)
        }

        override fun onRemoteVideoStateChanged(userId: String, deviceName: String, state: AVideoState) {
            dbyEventHandlerWrap?.onRemoteVideoStateChanged(userId, deviceName, state)
        }*/

        override fun onRemoteMicStateChange(uid: String, deviceName: String, state: AVideoState) {
            mSDKEventListener?.onRemoteMicStateChange(uid, deviceName, state)
        }

        override fun onSolNetworkInformation(information: SolNetworkInformation?) {
            super.onSolNetworkInformation(information)
            mSDKEventListener?.onSolNetworkInformation(information)
        }
    }

    override fun mgtMuteCamera(uids: Array<out String>) {
        val jsonArray = JSONArray()
        for (uid in uids) {
            jsonArray.put(uid)
        }
        val jsonObject = JSONObject()
        jsonObject.put("type","mgtMuteCamera")
        jsonObject.put("data", jsonArray)

        dbyEngine?.sendBroadcastMessage(jsonObject.toString()) { }
    }

    override fun mgtMuteAudio(uids: Array<out String>) {
        val jsonArray = JSONArray()
        for (uid in uids) {
            jsonArray.put(uid)
        }
        val jsonObject = JSONObject()
        jsonObject.put("type","mgtMuteAudio")
        jsonObject.put("data", jsonArray)

        dbyEngine?.sendBroadcastMessage(jsonObject.toString()) { }
    }

    override fun mgtMuteShareContent(uids: Array<out String>) {
        val jsonArray = JSONArray()
        for (uid in uids) {
            jsonArray.put(uid)
        }
        val jsonObject = JSONObject()
        jsonObject.put("type","mgtMuteShareContent")
        jsonObject.put("data", jsonArray)

        dbyEngine?.sendBroadcastMessage(jsonObject.toString()) { }
    }

}